<template>
  <div class="pre-production-planning">
    <!-- 顶部导航栏 -->
    <el-row type="flex" class="header-toolbar">
      <el-col :span="15">
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleSaveAndAdd">保存且新增</el-button>
        <el-button @click="handleSaveAsDraft">数据暂存</el-button>
        <el-button @click="handleDraftBox">草稿箱</el-button>
        <el-button @click="handleImport">导入</el-button>
        <el-button @click="handleDesign">设计</el-button>  
      </el-col>
    </el-row>

    <!-- 基本信息区域 -->
    <el-card class="basic-info">
      <h2 style="margin-left: 50%;">预生产计划</h2>
      <h3>基本信息</h3>
      <el-form :model="formData" label-width="120px">
        <tr>
          <td><el-form-item label="单据主题：">
          <el-input v-model="formData.title" style="width: 200px;"></el-input>
        </el-form-item></td>
        <td>
          <el-form-item label="单据编号：">
          <el-input v-model="formData.code" placeholder="保存后自动生成"></el-input>
        </el-form-item>
        </td>
        <td>
          <el-form-item label="来源单据类型：">
          <el-select v-model="formData.sourceType" placeholder="请选择" style="width: 200px;">
            <el-option label="无来源" value="none"></el-option>
          </el-select>
        </el-form-item>
        </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="制单人员：">
          <el-input v-model="formData.creator"></el-input>
        </el-form-item>
          </td>
          <td>
            <el-form-item label="制单日期：">
          <el-date-picker
            v-model="formData.date"
            type="date"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
          </td>
          <td>
            <el-form-item label="关联项目：">
          <el-input v-model="formData.project"></el-input>
        </el-form-item>
          </td>
        </tr> 
        <el-form-item label="备注">
          <el-input v-model="formData.project"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预生产计划明细表 -->
    <el-card class="detail-table">
      <h3>预生产计划明细</h3>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="60" label="序号"></el-table-column>
        
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="productCode" label="产品编号"></el-table-column>
        <el-table-column prop="spec" label="规格型号"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column prop="quantity" label="本次计划数量">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" @change="calculateTotal"></el-input-number>
          </template>
        </el-table-column>
        
        <el-table-column prop="deliveryDate" label="交货日期">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.deliveryDate"
              type="date"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </template>
        </el-table-column>
        
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="handleCopyRow(scope.$index)">复制行</el-button>
            <el-button @click="handleDeleteRow(scope.$index)">删</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="total">数量合计：{{ totalQuantity }}</div>
    </el-card>

    <!-- 附件区域 -->
    <div class="file-upload-container">
    <!-- 操作区 -->
    <div class="upload-header">
      <el-button type="primary" @click="handleUpload">附件</el-button>
      <el-upload
        ref="uploadRef"
        action="#"
        :auto-upload="false"
        multiple
        :file-list="fileList"
        :on-change="handleChange"
        :before-upload="beforeUpload"
        list-type="text"
        class="batch-upload"
      >
      <el-button icon="el-icon-upload">批量选择文件</el-button>
      </el-upload>
    </div>
    <!-- 文件列表区 -->
    <el-table :data="uploadedFiles" style="width: 100%" border class="uploaded-table">
      <el-table-column prop="name" label="文件名称"></el-table-column>
      <el-table-column prop="name" label="文件名称"></el-table-column>
      <el-table-column prop="size" label="大小">
        <template #default="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="uploader" label="上传人">
        <template #default="scope">
          {{ scope.row.uploader || '待填写' }}
        </template>
      </el-table-column>

      <el-table-column prop="uploadTime" label="上传时间">
        <template #default="scope">
          {{ formatDate(scope.row.uploadTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handlePreview(scope.row)">预览</el-button>
          <el-button type="danger" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const formData = ref({
  title: '',
  code: '',
  sourceType: 'none',
  creator: '',
  date: '',
  project: ''
})

const tableData = ref([
  {
    id: 1,
    productName: '',
    productCode: '',
    spec: '',
    unit: '',
    quantity: 0,
    deliveryDate: ''
  }
])

const attachments = ref([])

// 计算总数量
const totalQuantity = computed(() => {
  return tableData.value.reduce((sum, row) => sum + row.quantity, 0)
})

// 处理保存操作
const handleSave = () => {
  console.log('保存数据:', { formData: formData.value, tableData: tableData.value })
}

// 其他按钮事件处理函数
const handleSaveAndAdd = () => {/* ... */}
const handleSaveAsDraft = () => {/* ... */}
const handleDraftBox = () => {/* ... */}
const handleImport = () => {/* ... */}
const handleDesign = () => {/* ... */}

const handleCopyRow = (index) => {
  const newRow = { ...tableData.value[index], id: Date.now() }
  tableData.value.splice(index + 1, 0, newRow)
}

const handleDeleteRow = (index) => {
  tableData.value.splice(index, 1)
}

import dayjs from 'dayjs'

// 本地待上传文件列表（仅临时存储）
const localFiles = ref([])

// 已上传到服务器的文件列表
const uploadedFiles = ref([
  {
    name: '合同草案.pdf',
    size: 2048000,
    uploader: '张三',
    uploadTime: new Date(),
    status: 'success'
  }
])

const uploadRef = ref(null)

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
// 选择文件时的处理
const handleLocalChange = (file) => {
  // 只保留本地文件列表，不与已上传文件混合
  localFiles.value = [...localFiles.value, file.file]
}
// 上传前的校验
const beforeUpload = (file) => {
  console.log('准备上传文件:', file.name)
  return true
}



// 开始上传操作
const handleUpload = async () => {
  // 模拟上传过程
  for (const file of localFiles.value) {
    await new Promise(resolve => {
      setTimeout(() => {
        uploadedFiles.value.push({
          ...file,
          uploader: localStorage.getItem('username') || '系统',
          uploadTime: new Date()
        })
        localFiles.value = [] // 清空待上传列表
        resolve()
      }, 1000)
    })
  }
  this.$message.success('上传完成')
}

// 删除操作
const handleDelete = (index) => {
  uploadedFiles.value.splice(index, 1)
}
</script>

<style scoped>
.pre-production-planning {
  padding: 20px;
}

.header-toolbar {
  margin-bottom: 20px;
}

.basic-info, .detail-table, .attachment {
  margin-bottom: 30px;
}

.total {
  margin-top: 15px;
  color: #67c23a;
  font-weight: bold;
}

.file-list {
  margin-top: 10px;
  list-style: none;
  padding: 0;
}
.file-upload-container {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.upload-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.batch-upload {
  margin-left: auto;
}

.el-table {
  margin-top: 15px;
}

/* 表格表头增强 */
.el-table th {
  background-color: #f8f9fa !important;
  font-weight: 500;
  color: #333;
}
</style>